<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>

    .content {
        height: 500px;
        width: 200px;
        background: lightcoral;
    }

</style>
<body>
    
    <div class="content"></div>
    <div id="item"><h1>你好</h1></div>
    <div class="content"></div>
    <div class="content"></div>
    <div><button id="btn">回到顶部</button></div>
    <div><button id="btn2">回到特定元素</button></div>

</body>

<script>
    
    const scrollToTop = () => {
        const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop;
        console.log(scrollHeight);
        if (scrollHeight > 5) {
            // 窗口刷新的时候执行
            window.requestAnimationFrame(scrollToTop);
            window.scrollTo(0 ,scrollHeight - scrollHeight / 10);
        }
    }

    const scrollToTarget = (targetId) => {
        document.getElementById(targetId).scrollIntoView({ behavior: 'smooth' });
    }

    const btn = document.getElementById('btn');
    btn.addEventListener('click', () => {
        console.log('回到顶部');
        scrollToTop();
    })

    btn2.addEventListener('click', () => {
        console.log('回到特定元素');
        
        scrollToTarget('item');
    })

</script>

</html>